package com.lijiajia.cloud.authserver.service.impl.mongodb;

import com.lijiajia.cloud.authserver.pojo.mongodb.User;
import com.lijiajia.cloud.authserver.pojo.mongodb.UserConnection;
import com.lijiajia.cloud.authserver.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 用户服务 mongo实现
 *
 * @author lijiajia
 * @since 2019-4-28
 */
@Slf4j
@Service
public class MongoUserService implements UserService {

	private final MongoTemplate mongoTemplate;

	public MongoUserService(MongoTemplate mongoTemplate) {
		this.mongoTemplate = mongoTemplate;
	}

	@Override
	public User insert(User user) {
		mongoTemplate.insert(user);
		log.debug("users insert doc: {}", user);
		return user;
	}

	@Override
	public Optional<User> findById(String id) {
		Query query = new Query();
		query.addCriteria(
			Criteria.where(User.ID).is(id)
				.and(User.DELETED).is(false)
		);
		User user = mongoTemplate.findOne(query, User.class);
		return Optional.ofNullable(user);
	}

	@Override
	public Optional<User> findByUsername(String username) {
		Query query = Query.query(
			Criteria.where(User.USERNAME).is(username)
				.and(User.DELETED).is(false)
		);

		return Optional.ofNullable(mongoTemplate.findOne(query, User.class));
	}

	@Override
	public Optional<User> findByOpenId(String providerId, String openId) {
		Query query = Query.query(
			Criteria.where(UserConnection.PROVIDER_ID).is(providerId)
				.and(UserConnection.OPEN_ID).is(openId)
		);
		UserConnection connection = mongoTemplate.findOne(query, UserConnection.class);
		return connection == null ? Optional.empty() : findById(connection.getUserId());
	}

}
